//
//  BookShopViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-2-26.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "BookShopViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import "asyncimageview.h"
#import "CityShowViewController.h"
#import "BookDetailViewController.h"
#import "ChartViewController.h"
#import "MyOrderViewController.h"
#import "MainTabBarController.h"
#define TopViewH 38
#define CityTag 35

@interface BookShopViewController ()

@end

@implementation BookShopViewController

- (id)init
{
    if (self = [super init]) {
        // Custom initialization
        _BookDataArr = [[NSMutableArray alloc] init];
        _ShowAsyArr = [[NSMutableArray alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onChangeProResponse:)
                                                     name:NotProChg
                                                   object:nil];
        _OrderStr = [[NSString alloc] initWithFormat:@"sales"];
        
        NSDictionary* tDic0 = [NSDictionary dictionaryWithObjectsAndKeys:@"销量",@"name",@"sales",@"key", nil];
        NSDictionary* tDic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"评分",@"name",@"remark",@"key", nil];
        NSDictionary* tDic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"价格",@"name",@"pricea",@"key", nil];
        _TopNameIDArr = [[NSArray alloc] initWithObjects:tDic0,tDic1,tDic2, nil];
        
        
        _StarGrayImg= [[UIImage imageNamed:@"list_star_gray.png"] retain];
        _StarHalfImg= [[UIImage imageNamed:@"list_star_halt.png"] retain];
        _StarImg= [[UIImage imageNamed:@"list_star.png"] retain];
    }
    return self;
}

-(void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_StarGrayImg release];
    [_StarHalfImg release];
    [_StarImg release];
    [_TopNameIDArr release];
    [_OrderStr release];
    [_ShowAsyArr release];
    [_BookDataArr release];
    [_TagImgView release];
    [_TopView release];
    [_RightBtt release];
    [_BuysBtt release];
    [_NavBtt release];
    [_BookTableView release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
  
     m_titleBttBarItem = [[MainTabBarController setTitle:@"图书商城"] retain];
    
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    _BuysBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_BuysBtt setImage:[UIImage imageNamed:@"chart.png"] forState:UIControlStateNormal];
    _BuysBtt.frame =CGRectMake(240, 10, 24, 24);
    [_BuysBtt addTarget:self action:@selector(buysBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [_BuysBtt retain];
    
    _RightBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_RightBtt setImage:[UIImage imageNamed:@"orderlist.png"] forState:UIControlStateNormal];
    _RightBtt.frame =CGRectMake(286, 10, 24, 24);
    [_RightBtt addTarget:self action:@selector(orderBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [_RightBtt retain];
    
    //上部按钮
    _TopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, TopViewH)];
    [_TopView setBackgroundColor:[UIColor colorWithRed:235/255.f green:227/255.f blue:205/255.f alpha:1]];
    [self.view addSubview:_TopView];
    
    CALayer* tCLineLay = [CALayer layer];
    tCLineLay.frame =CGRectMake(56, 0, 1, TopViewH);
    [tCLineLay setBackgroundColor:[UIColor whiteColor].CGColor];
    [_TopView.layer addSublayer:tCLineLay];
    
    UIImageView* tMoreImgView = [[UIImageView alloc] initWithFrame:CGRectMake(40, (TopViewH-4)/2, 7, 4)];
    [tMoreImgView setImage:[UIImage imageNamed:@"more.png"]];
    [_TopView addSubview:tMoreImgView];
    [tMoreImgView release];
    UILabel* tKaoLab = [[UILabel alloc] initWithFrame:CGRectMake(4, (TopViewH-16)/2, 34, 16)];
    [tKaoLab setBackgroundColor:[UIColor clearColor]];
    [tKaoLab setText:@"国考"];
    tKaoLab.textAlignment = UITextAlignmentRight;
    [tKaoLab setFont:[UIFont systemFontOfSize:14]];
    [tKaoLab setTextColor:[UIColor darkGrayColor]];
    tKaoLab.tag = CityTag;
    [_TopView addSubview:tKaoLab];
    [tKaoLab release];
    UIButton* tKaoBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    tKaoBtt.frame =CGRectMake(4, 0, 46, TopViewH);
    [tKaoBtt addTarget:self action:@selector(kaoBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [_TopView addSubview:tKaoBtt];
    
    for (int i=0; i<3; i++) {
        UIButton* tTitBtt = [UIButton buttonWithType:UIButtonTypeCustom];
        tTitBtt.frame =CGRectMake(74+i*74, (TopViewH-16)/2, 74, 16);
        [tTitBtt setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [tTitBtt setTitle:[[_TopNameIDArr objectAtIndex:i] objectForKey:@"name"] forState:UIControlStateNormal];
        [tTitBtt.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [tTitBtt addTarget:self action:@selector(changeOrder:) forControlEvents:UIControlEventTouchUpInside];
        tTitBtt.tag = i;
        [_TopView addSubview:tTitBtt];
    }
    
    _TagImgView = [[UIImageView alloc] initWithFrame:CGRectMake(106, TopViewH-5, 10, 5)];
    [_TagImgView setImage:[UIImage imageNamed:@"trg.png"]];
    [_TopView addSubview:_TagImgView];
    
    
    
    _BookTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, TopViewH, 320, self.view.frame.size.height-44-TopViewH) style:UITableViewStylePlain];
    _BookTableView.delegate = self;
    _BookTableView.dataSource = self;
    _BookTableView.separatorColor = SEPARATOR_COLOR;
    [_BookTableView setBackgroundColor:BACKGROUND_COLOR];
    [self.view addSubview:_BookTableView];
    
    [self setCityLab];
    _NowPage =1;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getProductList&category_id=%@&order_by=%@&page=1&pageSize=20",RequestCurrentURL,tAppDel.m_Province_id,_OrderStr];
    [self requestListData:tURLStr];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
    [self.navigationController.navigationBar addSubview:_BuysBtt];
    [self.navigationController.navigationBar addSubview:_RightBtt];
    if ([m_titleBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
    }
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [_BuysBtt removeFromSuperview];
    [_RightBtt removeFromSuperview];
    if ([m_titleBttBarItem superview]) {
        [m_titleBttBarItem removeFromSuperview];
    }
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) setCityLab
{
    UILabel* tCityLab = (UILabel*)[_TopView viewWithTag:CityTag];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* tEnumCityStr = nil;
    for (NSDictionary* tCityDic in tAppDel.m_CityDataArr) {
        tEnumCityStr = [NSString stringWithFormat:@"%d",[[tCityDic objectForKey:@"id"] intValue]];
        if ([tEnumCityStr isEqualToString:tAppDel.m_Province_id]) {
            [tCityLab setText:[tCityDic objectForKey:@"name"]];
            return;
        }
    }
}

//考点击
-(void) kaoBttPressed
{
    CityShowViewController* tCityVC = [[CityShowViewController alloc] init];
    tCityVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tCityVC animated:YES];
    [tCityVC release];
}

- (void)onChangeProResponse:(NSNotification *)notification
{
    [self setCityLab];
    [_ShowAsyArr removeAllObjects];
    [_BookDataArr removeAllObjects];
    _NowPage =1;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getProductList&category_id=%@&order_by=%@&page=1&pageSize=20",RequestCurrentURL,tAppDel.m_Province_id,_OrderStr];
    [self requestListData:tURLStr];
}

-(void) buysBttPressed
{
    ChartViewController* tChartVC = [[ChartViewController alloc] init];
    tChartVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tChartVC animated:YES];
    [tChartVC release];
}
-(void) orderBttPressed
{
    MyOrderViewController* iMyOrder = [[MyOrderViewController alloc] init];
    //iMyOrder.hidesBottomBarWhenPushed = YES;
    iMyOrder.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:iMyOrder animated:YES];
    [iMyOrder release];
    
}
//专题数据切换
-(void) changeOrder:(UIButton*)f_sender
{
 
    [UIView beginAnimations:nil context:nil];
    int tTypeIndex = f_sender.tag;
    CGRect aFrame =_TagImgView.frame;
    aFrame.origin.x = 106+tTypeIndex*74;
    _TagImgView.frame = aFrame;
    [UIView commitAnimations];
    [_ShowAsyArr removeAllObjects];
    [_BookDataArr removeAllObjects];
    
    _NowPage =1;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getProductList&category_id=%@&order_by=%@&page=1&pageSize=20",RequestCurrentURL,tAppDel.m_Province_id,_OrderStr];
    [self requestListData:tURLStr];
    
    
}

-(void) requestListData:(NSString*)f_URLStr
{
    [self addHudLoad];
    _NowPage++;
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:f_URLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestListFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestListFinish:)];
    [tRequestPage startAsynchronous];
}

-(void) requestListFail:(ASIHTTPRequest*)request
{
    _NowPage--;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestListFinish:(ASIHTTPRequest*)request
{
    NSError* tError;

    NSString* tReqStr = [request responseString];

    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            id tRealDataDic = [tDataDic objectForKey:@"data"];
            if ([tRealDataDic isKindOfClass:[NSDictionary class]]) {
                NSArray* tListArr = [tRealDataDic objectForKey:@"list"];
                [_BookDataArr addObjectsFromArray:tListArr];
                
                for (NSDictionary* tDic in tListArr) {
                    NSString* tImgStr =[tDic objectForKey:@"image"];
                    if ([tImgStr length] > 0) {
                        AsyncImageView* tImgView = [[AsyncImageView alloc] initWithFrame:CGRectMake(6, 6, 60, 60)];
                        tImgView.m_BoolSetImage =YES;
                        tImgView._numStateRequested =need_Request;
                        tImgView._imageRequestURL =tImgStr;
                        [_ShowAsyArr addObject:tImgView];
                        [tImgView customLoadImageFromURL];
                        [tImgView release];
                    }else{
                        [_ShowAsyArr addObject:@""];
                    }
                }
            }
            [_BookTableView reloadData];
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:NO delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}


#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}

#pragma mark-
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BookDetailViewController* tBookDetVC = [[BookDetailViewController alloc] init];
    tBookDetVC.navigationItem.hidesBackButton =YES;
    tBookDetVC.hidesBottomBarWhenPushed =YES;
    NSDictionary* tBookDic = [_BookDataArr objectAtIndex:indexPath.row];
    tBookDetVC.m_BookIDStr =[NSString stringWithFormat:@"%d",[[tBookDic objectForKey:@"id"] intValue]];
    [self.navigationController pushViewController:tBookDetVC animated:YES];
    [tBookDetVC release];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 74;

}
#pragma mark-
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [_BookDataArr count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* tCell= nil;
    int tRow = indexPath.row;

    static NSString* s_CellStr = @"kcell";
    tCell = [tableView dequeueReusableCellWithIdentifier:s_CellStr];
    if (tCell  == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:s_CellStr] autorelease];
        
        tCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        UILabel* tTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(75, 6, 220,20)];
        [tTitleLab setBackgroundColor:[UIColor clearColor]];
        [tTitleLab setFont:[UIFont boldSystemFontOfSize:15]];
        tTitleLab.tag =50;
        [tCell addSubview:tTitleLab];
        [tTitleLab release];
        
        UILabel* tDesLab = [[UILabel alloc] initWithFrame:CGRectMake(75, 28, 240,24)];
        [tDesLab setBackgroundColor:[UIColor clearColor]];
        [tDesLab setTextColor:[UIColor colorWithRed:251/255.f green:153/255.f blue:0 alpha:1]];
        [tDesLab setFont:[UIFont systemFontOfSize:18]];
        tDesLab.tag =51;
        [tCell addSubview:tDesLab];
        [tDesLab release];
        
        for (int i=0; i<5; i++) {
           UIImageView* tStarImgView = [[UIImageView alloc] initWithFrame:CGRectMake(75+i*10, 56, 8, 8)];
            tStarImgView.tag =10+i;
            [tCell addSubview:tStarImgView];
            [tStarImgView release];
        }
        
    }
    for (id tSubObject in tCell.subviews) {
        if ([tSubObject isKindOfClass:[AsyncImageView class]]) {
            [tSubObject removeFromSuperview];
        }
    }
    id tAsyObject = [_ShowAsyArr objectAtIndex:tRow];
    BOOL tIsHaveImg =NO;
    if ([tAsyObject isKindOfClass:[AsyncImageView class]]) {
        [tCell addSubview:tAsyObject];
        [tAsyObject customLoadImageFromURL];
        tIsHaveImg = YES;
    }
    UILabel* tTitleLab = (UILabel*)[tCell viewWithTag:50];
    UILabel* tDesLab = (UILabel*)[tCell viewWithTag:51];
    NSDictionary* tBookDic = [_BookDataArr objectAtIndex:indexPath.row];
    [tTitleLab setText:[tBookDic objectForKey:@"name"]];
    [tDesLab setText:[NSString stringWithFormat:@"¥ %d",[[tBookDic objectForKey:@"price"] intValue]]];
    float tMark = [[tBookDic objectForKey:@"remark"] floatValue];
    int tTMark =tMark*2;
    
    UIImageView* tStarImgView0 = (UIImageView*)[tCell viewWithTag:10];
    UIImageView* tStarImgView1 = (UIImageView*)[tCell viewWithTag:11];
    UIImageView* tStarImgView2 = (UIImageView*)[tCell viewWithTag:12];
    UIImageView* tStarImgView3 = (UIImageView*)[tCell viewWithTag:13];
    UIImageView* tStarImgView4 = (UIImageView*)[tCell viewWithTag:14];

    [tStarImgView0 setImage:_StarGrayImg];
    [tStarImgView1 setImage:_StarGrayImg];
    [tStarImgView2 setImage:_StarGrayImg];
    [tStarImgView3 setImage:_StarGrayImg];
    [tStarImgView4 setImage:_StarGrayImg];
    int tStarNum = tTMark/2;
    BOOL tBoolHStar = tTMark%2;
    for (int i=0; i<tStarNum; i++) {
        UIImageView* tStarImgView0 = (UIImageView*)[tCell viewWithTag:10+i];
        [tStarImgView0 setImage:_StarImg];
    }
    if (tBoolHStar == 1) {
        UIImageView* tStarImgView = (UIImageView*)[tCell viewWithTag:10+tStarNum];
        [tStarImgView setImage:_StarHalfImg];
    }
    return tCell;
}
#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    int tPosyH =scrollView.contentSize.height-scrollView.frame.size.height;
    if (tPosyH < 0) {
        tPosyH = 0;
    }
    if (scrollView.contentOffset.y > tPosyH+30) {
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getProductList&category_id=%@&order_by=%@&page=%d&pageSize=20",RequestCurrentURL,tAppDel.m_Province_id,_OrderStr,_NowPage];
        [self requestListData:tURLStr];
    }
    
}

@end
